package me.zingon.self.bigdispatcher.job;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import me.zingon.self.bigdispatcher.constant.JobDataKey;
import me.zingon.self.bigdispatcher.entity.NacosJob;
import me.zingon.self.bigdispatcher.entity.NacosJobLog;
import me.zingon.self.bigdispatcher.exception.ServiceException;
import me.zingon.self.bigdispatcher.service.NacosJobLogService;
import me.zingon.self.bigdispatcher.util.NacosCaller;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * @author ztc 1423047407@qq.com
 * @version 1.0
 * @date 2020-12-29 13:56
 */
@Slf4j
public class NacosJobDetail extends QuartzJobBean {

    @Autowired
    NacosCaller caller;

    @Autowired
    NacosJobLogService nacosJobLogService;

    @Override
    protected void executeInternal(JobExecutionContext context) {
        NacosJob job = JSONUtil.toBean(context.getTrigger().getJobDataMap().getString(JobDataKey.JOB.toString()), NacosJob.class);
        if (caller == null) {
            throw new ServiceException("Job中未设置 nacosCaller");
        }
        String host = caller.getService(job.getNamespaceId(), job.getGroupName(), job.getServiceName());
        log.info("get host:{}", host);


        NacosJobLog jobLog=new NacosJobLog();
        jobLog.setExecTime(new Date());
        jobLog.setNacosJobId(job.getId());
        nacosJobLogService.add(jobLog);

        String body = null;
        if ("GET".equals(job.getMethod().toUpperCase())) {
            body = HttpUtil.get(host + job.getPath(), job.getParamsM());
        } else if ("POST".equals(job.getMethod().toUpperCase())) {
            body = HttpUtil.post(host + job.getPath(), job.getParams());
        }

        jobLog.setCompleTime(new Date());
        jobLog.setResult(body);
        nacosJobLogService.updateById(jobLog);


        log.info("call :{},result:{}", host + job.getPath(), body);
    }
}
